<!-- modules/HorizontalMixMenu.vue - 修复版本 -->
<template>
  <!-- 🎯 一级菜单传送到头部 -->
  <Teleport 
    v-if="primaryTeleportReady" 
    to="#header-menu-container"
  >
    <div class="horizontal-mix-primary">
      <el-menu
        mode="horizontal"
        :default-active="activeFirstLevelMenuKey"
        :collapse-transition="false"  
        class="vilan-menu primary-menu"
        @select="handlePrimarySelect"
      >
        <!-- 静态一级菜单 -->
        <template v-if="!useDynamic">
          <el-menu-item index="dashboard">
            <el-icon><Odometer /></el-icon>
            仪表板
          </el-menu-item>
          
          <el-menu-item index="system">
            <el-icon><Setting /></el-icon>
            系统管理
          </el-menu-item>
          
          <el-menu-item index="user">
            <el-icon><Avatar /></el-icon>
            用户中心
          </el-menu-item>
        </template>
        
        <!-- 🎯 动态一级菜单 -->
        <template v-else>
          <el-menu-item 
            v-for="menu in firstLevelMenus" 
            :key="menu.key"
            :index="menu.key"
          >
            <el-icon v-if="menu.icon">
              <component :is="getMenuIcon(menu.icon)" />
            </el-icon>
            {{ menu.label }}
          </el-menu-item>
        </template>
      </el-menu>
    </div>
  </Teleport>
  
  <!-- 🎯 二级菜单传送到侧边栏 -->
  <Teleport 
    v-if="subTeleportReady && showSubMenu" 
    to="#sider-menu-container-sub"
  >
    <div class="horizontal-mix-sub">
      <div class="sub-menu-header">
        <h3>{{ currentMenuTitle }}</h3>
      </div>
      
      <el-menu
        mode="vertical"
        :default-active="$route.path"
        :router="true"
        :collapse-transition="false" 
        class="vilan-menu sub-menu"
      >
        <!-- 静态子菜单 -->
        <template v-if="!useDynamic">
          <template v-if="activeFirstLevelMenuKey === 'system'">
            <el-menu-item index="/system/user">
              <el-icon><User /></el-icon>
              <template #title>用户管理</template>
            </el-menu-item>
            <el-menu-item index="/system/role">
              <el-icon><UserFilled /></el-icon>
              <template #title>角色管理</template>
            </el-menu-item>
            <el-menu-item index="/system/menu">
              <el-icon><Menu /></el-icon>
              <template #title>菜单管理</template>
            </el-menu-item>
          </template>
          
          <template v-else-if="activeFirstLevelMenuKey === 'user'">
            <el-menu-item index="/user/profile">
              <el-icon><UserFilled /></el-icon>
              <template #title>个人资料</template>
            </el-menu-item>
            <el-menu-item index="/user/setting">
              <el-icon><Tools /></el-icon>
              <template #title>账户设置</template>
            </el-menu-item>
          </template>
        </template>
        
        <!-- 🎯 动态子菜单 -->
        <template v-else>
          <el-menu-item
            v-for="child in childLevelMenus"
            :key="child.key"
            :index="child.path"
          >
            <el-icon v-if="child.icon">
              <component :is="getMenuIcon(child.icon)" />
            </el-icon>
            <template #title>{{ child.label }}</template>
          </el-menu-item>
        </template>
      </el-menu>
    </div>
  </Teleport>
</template>

<script setup>
import { computed, ref, onMounted, nextTick, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useLayoutManage } from '@/layouts/layoutManage.js'
import {
  Odometer,
  Setting,
  Avatar,
  User,
  UserFilled,
  Menu,
  Tools,
  InfoFilled,
  Document,
  DataBoard,
  EditPen
} from '@element-plus/icons-vue'

const props = defineProps({
  useDynamic: Boolean,
  menuData: Array,
  config: Object
})

const route = useRoute()
const router = useRouter()

// 🎯 调试：打印 props
console.log('🔍 [HorizontalMixMenu] Props:', {
  useDynamic: props.useDynamic,
  menuDataCount: props.menuData?.length
})

// 🎯 混合菜单管理
const {
  activeFirstLevelMenuKey,
  setActiveFirstLevelMenuKey,
  firstLevelMenus,
  childLevelMenus
} = useLayoutManage()

// 🎯 调试：监听菜单数据
console.log('🔍 [HorizontalMixMenu] 混合菜单数据:', {
  activeKey: activeFirstLevelMenuKey.value,
  firstLevelCount: firstLevelMenus.value.length,
  firstLevelMenus: firstLevelMenus.value,
  childLevelCount: childLevelMenus.value.length,
  childLevelMenus: childLevelMenus.value
})

// 🎯 控制两个 Teleport 的时机
const primaryTeleportReady = ref(false)
const subTeleportReady = ref(false)

// 🎯 是否显示子菜单（基于实际子菜单数量）
const showSubMenu = computed(() => {
  const hasChildren = childLevelMenus.value && childLevelMenus.value.length > 0
  console.log('🔍 [HorizontalMixMenu] showSubMenu 计算:',
    'hasChildren:', hasChildren,
    'childCount:', childLevelMenus.value?.length || 0,
    'activeKey:', activeFirstLevelMenuKey.value,
    'childMenus:', childLevelMenus.value
  )
  return hasChildren
})

// 🎯 当前菜单标题
const currentMenuTitle = computed(() => {
  // 🎯 从 firstLevelMenus 中查找当前激活菜单的标题
  const activeMenu = firstLevelMenus.value.find(menu => menu.key === activeFirstLevelMenuKey.value)
  return activeMenu?.label || ''
})

// 🎯 等待容器就绪
onMounted(async () => {
  console.log('🚀 [水平混合] 组件已挂载')
  console.log('📊 [水平混合] 初始状态:', {
    activeFirstLevelMenuKey: activeFirstLevelMenuKey.value,
    firstLevelMenus: firstLevelMenus.value,
    childLevelMenus: childLevelMenus.value,
    showSubMenu: showSubMenu.value
  })
  
  await nextTick()
  
  // 检查头部容器
  const headerTarget = document.querySelector('#header-menu-container')
  if (headerTarget) {
    primaryTeleportReady.value = true
    console.log('✅ 头部容器就绪')
  }
  
  // 检查侧边栏容器
  const siderTarget = document.querySelector('#sider-menu-container-sub')
  if (siderTarget) {
    subTeleportReady.value = true
    console.log('✅ 侧边栏容器就绪')
  } else {
    // 延迟重试
    setTimeout(() => {
      const retryTarget = document.querySelector('#sider-menu-container-sub')
      if (retryTarget) {
        subTeleportReady.value = true
        console.log('✅ 侧边栏容器延迟就绪')
      }
    }, 100)
  }
})

// 🎯 事件处理
function handlePrimarySelect(index) {
  console.log('🎯 [HorizontalMixMenu] 一级菜单点击:', index)
  console.log('📊 [HorizontalMixMenu] 点击前状态:', {
    oldActiveKey: activeFirstLevelMenuKey.value,
    oldChildMenus: childLevelMenus.value
  })
  
  setActiveFirstLevelMenuKey(index)
  
  console.log('📊 [HorizontalMixMenu] 点击后状态:', {
    newActiveKey: activeFirstLevelMenuKey.value,
    newChildMenus: childLevelMenus.value
  })
  
  // 如果是仪表板，直接跳转
  if (index === 'dashboard') {
    router.push('/dashboard')
  }
}

// 🎯 监听子菜单变化
watch(childLevelMenus, (newVal) => {
  console.log('🔄 [水平混合] 子菜单变化:', {
    count: newVal.length,
    menus: newVal,
    showSubMenu: showSubMenu.value
  })
}, { deep: true })

// 🎯 监听激活菜单变化
watch(activeFirstLevelMenuKey, (newVal) => {
  console.log('🔄 [水平混合] 激活菜单变化:', {
    newKey: newVal,
    childLevelMenus: childLevelMenus.value.length,
    showSubMenu: showSubMenu.value
  })
})

// 图标映射
function getMenuIcon(iconName) {
  // 🎯 图标映射表（兼容小写和大写）
  const iconMap = {
    'dashboard': Odometer,
    'system': Setting,
    'user': Avatar,
    'role': UserFilled,
    'menu': Menu,
    'tools': Tools,
    'document': Document,
    'Odometer': Odometer,
    'Setting': Setting,
    'Avatar': Avatar,
    'User': User,
    'UserFilled': UserFilled,
    'Menu': Menu,
    'Tools': Tools,
    'InfoFilled': InfoFilled,
    'Document': Document,
    'DataBoard': DataBoard,
    'EditPen': EditPen
  }
  return iconMap[iconName] || Menu
}

// 🎯 监听一级菜单变化，重新检查子菜单容器
watch(activeFirstLevelMenuKey, async () => {
  await nextTick()
  // 重新检查子菜单容器是否就绪
  const siderTarget = document.querySelector('#sider-menu-container-sub')
  subTeleportReady.value = !!siderTarget
  console.log('🔄 [HorizontalMixMenu] 激活菜单变化后检查容器:', {
    found: !!siderTarget,
    subTeleportReady: subTeleportReady.value
  })
})

// 🎯 监听 showSubMenu 变化，确保容器就绪
watch(showSubMenu, (newVal) => {
  if (newVal) {
    // 使用 setTimeout 确保 GlobalSider 完全渲染
    setTimeout(() => {
      const siderTarget = document.querySelector('#sider-menu-container-sub')
      if (siderTarget) {
        subTeleportReady.value = true
        console.log('✅ [HorizontalMixMenu] showSubMenu 变化后容器就绪')
      } else {
        console.warn('⚠️ [HorizontalMixMenu] showSubMenu 为 true 但容器未找到，再次重试...')
        // 再次重试
        setTimeout(() => {
          const retryTarget = document.querySelector('#sider-menu-container-sub')
          if (retryTarget) {
            subTeleportReady.value = true
            console.log('✅ [HorizontalMixMenu] 重试后容器就绪')
          } else {
            console.error('❌ [HorizontalMixMenu] 容器始终未找到')
          }
        }, 100)
      }
    }, 0)
  }
}, { immediate: true })
</script>

<style lang="scss" scoped>
// 🎯 头部一级菜单样式
.horizontal-mix-primary {
  height: 100%;
  flex: 1;
  
  .primary-menu {
    border: none;
    background: transparent;
    height: 100%;
    
    // ✅ 禁用动画避免闪烁
    * {
      transition: background-color 0.2s ease !important;
    }
    
    .el-menu-item {
      border-radius: 6px;
      margin: 0 4px;
      height: calc(100% - 8px);
      margin-top: 4px;
      
      &:hover {
        background: var(--el-color-primary-light-9);
      }
      
      &.is-active {
        background: var(--el-color-primary-light-8);
        color: var(--el-color-primary);
        border-bottom: 2px solid var(--el-color-primary);
      }
    }
  }
}

// 🎯 侧边栏二级菜单样式
.horizontal-mix-sub {
  width: 100%;
  height: 100%;
  background: #fafafa;  // 🎨 简约浅灰色背景
  
  .sub-menu-header {
    height: 48px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 16px;
    border-bottom: 1px solid #e8e8e8;  // 更柔和的边框
    background: #ffffff;  // 白色头部，与浅灰背景形成对比
    
    h3 {
      font-size: 14px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      margin: 0;
    }
  }
  
  .sub-menu {
    border: none;
    background: transparent;
    
    // ✅ 禁用动画避免闪烁
    * {
      transition: background-color 0.2s ease !important;
    }
    
    .el-menu-item {
      border-radius: 8px;  // 更圆润的圆角
      margin: 4px 12px;  // 更大的边距
      
      &:hover {
        background: #ffffff;  // 悬停时白色背景
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);  // 轻微阴影
      }
      
      &.is-active {
        background: var(--el-color-primary);  // 激活时主题色背景
        color: #ffffff;  // 白色文字
        font-weight: 500;
      }
    }
  }
}
</style>